#include "ctl_gpio.h"

bool CTL_GPIO::writeValue(const std::string& filename, const std::string& value) {
    std::stringstream oss;
    oss.str("");
    std::ofstream file(gpioPath + filename);
    if (!file.is_open()) {
        oss << "无法打开文件: " << gpioPath + filename;
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "writeValue", "%{public}s", oss.str().c_str());
        return false;
    }
    file << value;
    oss << "write value:" << gpioPath << filename;
    return true;
}

// 导出GPIO
bool CTL_GPIO::exportGPIO() {
    std::stringstream oss;
    oss.str("");
    std::ofstream exportFile("/sys/class/gpio/export");
    if (!exportFile.is_open()) {
        oss  << "无法导出GPIO" << gpioNumber << ": 权限不足或GPIO已导出";
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "exportGPIO", "%{public}s", oss.str().c_str());
        return false;
    }
    exportFile << gpioNumber;
    oss << "export gpio num:"<< gpioNumber;
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "exportGPIO", "%{public}s", oss.str().c_str());
    return true;
}

// 取消导出GPIO
bool CTL_GPIO::unexportGPIO() {
    std::stringstream oss;
    oss.str("");
    std::ofstream unexportFile("/sys/class/gpio/unexport");
    if (!unexportFile.is_open()) {
        oss  << "无法取消导出GPIO" << gpioNumber;
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "unexportGPIO", "%{public}s", oss.str().c_str());
        return false;
    }
    unexportFile << gpioNumber;
    return true;
}

// 读取GPIO电平
std::string CTL_GPIO::getValue() {
    std::stringstream oss;
    oss.str("");
    std::ifstream valueFile(gpioPath + "value");
    if (!valueFile.is_open()) {
        oss << "无法读取GPIO" << gpioNumber << "的值";
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "getValue", "%{public}s", oss.str().c_str());
        return "";
    }
    
    std::string value;
    valueFile >> value;
    oss <<"get value:" << gpioPath << "value :"<<value;
    OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "getValue", "%{public}s", oss.str().c_str());
    return value;
}
#if 0
int test() {
    const int gpioPin = 17;  // GPIO17 (物理引脚11)
    GPIO gpio(gpioPin);

    // 导出GPIO
    if (!gpio.exportGPIO()) return 1;
    std::cout << "GPIO" << gpioPin << " 导出成功" << std::endl;

    // 设置为输出模式
    if (!gpio.setDirection("out")) return 1;
    std::cout << "GPIO" << gpioPin << " 设置为输出模式" << std::endl;

    // 循环控制电平（闪烁LED）
    for (int i = 0; i < 5; ++i) {
        gpio.setValue("1");  // 高电平
        std::cout << "GPIO" << gpioPin << " 高电平" << std::endl;
        usleep(500000);      // 延时500ms

        gpio.setValue("0");  // 低电平
        std::cout << "GPIO" << gpioPin << " 低电平" << std::endl;
        usleep(500000);      // 延时500ms
    }

    // 取消导出GPIO
    if (!gpio.unexportGPIO()) return 1;
    std::cout << "GPIO" << gpioPin << " 取消导出成功" << std::endl;

    return 0;
}
#endif